package com.niren.relay.netty;

import com.niren.relay.common.dt.DateTime;

import java.util.Date;

public class TimeoutCheckHandler implements Runnable {
	TcpServerHandler TcpServer = null;
	public TimeoutCheckHandler(TcpServerHandler tcpServer) {
		this.TcpServer = tcpServer;
	}
	
    @Override
    public void run() {
    	System.out.println("Timeout Thread Start!");
        while(true){
    		
        	try {
				Thread.sleep(1000);//1秒运行一次超时检测 
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		//进行超时检测
    		for(ClientState client : this.TcpServer.ctxMap.values()) {
    			int sec = DateTime.calcTimeSecInterval(client.lastOnlineTime,new Date());
    			//大于30s超时
    			if(sec < 30) continue;
    			//30s内无任何通信，认为离线，30s后 ，认为离线，关闭连接
    			client.closeClient();//timeout , close client
    			client.setCommStatus(0);//0为离线
    			//更新数据库中的在线状态为离线
    			//这个在你数据库里是有一个表与设备进行对应的
    		}
        }
    }
}
